import { Injectable } from '@angular/core';
import {observable, Observable} from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class SocketService {
  public ws :WebSocket | undefined;

  constructor() { }

  connectServer(username:string): Observable<any>{
    this.ws=new WebSocket('wss://192.168.1.3:6466/peercon?Username='+username);
    return new Observable<any>(observable=>{
      this.ws!.onmessage=(event)=>observable.next(event.data);
      this.ws!.onerror = (event) => observable.error(event); // 失败
      this.ws!.onclose = (event) => observable.complete(); // 完成后，要结束

    })
  }

  // 向服务器端发送消息
  sendMessage(message: any) {
    let that = this;
    // console.log(this.ws)
    if(this.ws){
      if (this.ws.readyState===1) {
        this.ws.send(JSON.stringify(message));
      }else{
        // console.log(this.ws.readyState)
      }
    }else{
      // socket可能还没连接成功，那么延迟一秒再发送消息
      setTimeout(function () {
        that.ws!.send(JSON.stringify(message));
      },1000)
    }
  }


  close(){
    this.ws?.close();
  }
}
